package com.ngkj.zmfptback.sys.service.write.impl;

import com.ngkj.zmfptback.sys.bean.AuthorityEntity;
import com.ngkj.zmfptback.sys.bean.OperationEntity;
import com.ngkj.zmfptback.sys.mapper.read.AuthReadMapper;
import com.ngkj.zmfptback.sys.mapper.write.AuthWriteMapper;
import com.ngkj.zmfptback.sys.mapper.write.OperationWriteMapper;
import com.ngkj.zmfptback.sys.mapper.write.RoleAuthWriteMapper;
import com.ngkj.zmfptback.sys.service.write.OperationWriteService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author ChenHN
 * @since 2021/12/23 creation
 **/
@Service
@Transactional(propagation = Propagation.REQUIRED)
public class OperationWriteServiceImpl implements OperationWriteService {

    @Resource
    private OperationWriteMapper operationWriteMapper;

    @Resource
    private AuthWriteMapper authWriteMapper;

    @Resource
    private AuthReadMapper authReadMapper;

    @Resource
    private RoleAuthWriteMapper roleAuthWriteMapper;

    /**
     * 添加oper 同时更新auth
     * @param operationEntity
     */
    @Override
    public void addOper(OperationEntity operationEntity) {
        operationWriteMapper.addOper(operationEntity);
        AuthorityEntity authorityEntity = new AuthorityEntity();
        authorityEntity.setDescription(operationEntity.getOperName());
        authorityEntity.setFunId(operationEntity.getId());
        authorityEntity.setAuthType("OPER");
        authorityEntity.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        authWriteMapper.addAuth(authorityEntity);
    }

    @Override
    public void editOper(OperationEntity operationEntity) {
        operationWriteMapper.editOper(operationEntity);
        authWriteMapper.editAuthDescription( "OPER",operationEntity.getId(),operationEntity.getOperName());
    }


    /**
     * 删除oper 同时删除auth 及其 role_auth
     * @param id
     */
    @Override
    public void deleteOper(Long id) {
        operationWriteMapper.deleteOper(id);
        AuthorityEntity oper = authReadMapper.getAuthIdByTypeAndFunId("OPER", id);
        long authId = oper.getId();
        authWriteMapper.deleteAuthById(authId);
        roleAuthWriteMapper.deleteRoleAuthByAuthId(authId);
    }
}
